// 地图
export default class Map {
  constructor(el, rect = 10) {
    this.el = el;
    this.rect = rect;
    this.data = [];
    // 初始化长宽
    this.rows = Math.ceil(Map.getStyle(el, 'height') / rect);
    this.cells = Math.ceil(Map.getStyle(el, 'width') / rect);
    Map.setStyle(el, 'height', this.rows * rect);
    Map.setStyle(el, 'width', this.cells * rect);
  }

  static getStyle(el, attr) {
    return parseFloat(getComputedStyle(el)[attr]);
  }

  static setStyle(el, attr, val) {
    el.style[attr] = val + 'px';
  }

  // 添加数据
  setData(newData) {
    this.data = this.data.concat(newData);
  }
  
  // 清除数据
  clearData() {
    this.data.length = 0;
  }
  
  // 判断数据中是否包含新数据
  include({ x, y }) {
    return this.data.some(item => item.x == x && item.y == y);
  }

  // 渲染地图
  render() {
    this.el.innerHTML = this.data.map(item => {
      return `
        <span
          style="position: absolute; left: ${item.x * this.rect}px; top: ${item.y * this.rect}px; width: ${this.rect}px; height: ${this.rect}px; background-color: ${item.color}">
        </span>`;
    }).join('');
  }
}